package cn.vic.util;


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述：
 */
public class StringUtils {

    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isNotEmpty(final CharSequence str) {
        return !isEmpty(str);
    }

    public static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (Character.isWhitespace(cs.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }

    public static boolean isNotBlank(final CharSequence cs) {
        return !isBlank(cs);
    }

    public static String securityProduce(int length) {
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        int len = charSet.length();
        for (int i = 0; i < length; i++) {
            sb.append(charSet.charAt(r.nextInt(len - 1)));
        }
        return sb.toString();
    }

    public static String removeZeroDate(String date) {

        if (null != date && !"".equals(date)) {
            if (date.lastIndexOf(".") > -1)
                date = date.substring(0, date.lastIndexOf("."));
        }
        return date;
    }

    /**
     * 功能：不定长参数,其中一个参数为null或空则返回true,负责返回false
     *
     * @param str
     * @return boolean
     */
    public static boolean isEmpty(String... str) {
        for (String s : str) {
            if (StringUtils.isEmpty(s)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 功能：不定长参数,其中一个参数为null或空或为空格字符串则返回true,负责返回false
     *
     * @param str
     * @return boolean
     */
    public static boolean isBlank(String... str) {
        for (String s : str) {
            if (StringUtils.isBlank(s))
                return true;
        }
        return false;
    }

    private static String charSet = "0123456789";

    public static List<Integer> listConvert(Collection<String> list) {
        List<Integer> lint = new ArrayList<>();
        for (String str : list) {
            if (!str.matches("^([0-9])+$")) {
                continue;
            }
            int i = Integer.parseInt(str);
            lint.add(i);
        }
        return lint;
    }



    /***
     * 判断手机号码是否合法
     * 1开头的13位数字
     *
     * @param str
     * @return
     */
    public static boolean isMobile(String... str) {
        Pattern pattern = Pattern.compile("^1\\d{10}");//^(1[3|5|8])\\d{9}$
        for (String s : str) {
            Matcher matcher = pattern.matcher(s);
            return matcher.matches();
        }
        return false;
    }

    /**
     * 功能：判断字符串是否是数值. 默认允许有正负号,默认允许有小数点
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        boolean sign = true;
        int point_bef = Integer.MAX_VALUE;// 小数点前有几位
        int point_aft = Integer.MAX_VALUE;// 小数点后有几位
        return isNumeric(str, sign, point_bef, point_aft);
    }

    /**
     * 功能：判断字符串是否是数值
     *
     * @param str
     * @param sign  是否允许有正负号
     * @param point 是否允许有小数点
     * @return
     */
    public static boolean isNumeric(String str, boolean sign, boolean point) {
        int point_bef = Integer.MAX_VALUE;// 小数点前有几位
        int point_aft = Integer.MAX_VALUE;// 小数点后有几位
        if (!point)
            point_aft = 0;

        return isNumeric(str, sign, point_bef, point_aft);
    }

    /**
     * 功能：判断字符串是否是数值
     *
     * @param str
     * @param sign      是否允许有正负号
     * @param point_bef 精度,小数点前有几位
     * @param point_aft 精度,小数点后有几位,如果为0,则为整数
     * @return
     */
    public static boolean isNumeric(String str, boolean sign, int point_bef, int point_aft) {
        if (StringUtils.isBlank(str)) {
            return false;
        }
        boolean point = true;// 是否允许小数点
        if (point_aft == 0) {
            point = false;// 不允许有小数点
        } else {
            point = true;
        }
        StringBuffer pat = new StringBuffer();
        if (sign) {
            pat.append("[+|-]?");
        }
        if (point_bef == 0) {
            pat.append("[0]");
        } else {
            pat.append("[0-9]{1,");
            pat.append(point_bef);
            pat.append("}");
        }
        if (point && str.indexOf(".") != -1) {// 允许小数点,并且有小数点
            pat.append("[.]");
            pat.append("[0-9]{1,");// 小数点后必须有一位
            pat.append(point_aft);
            pat.append("}");
        }
        Pattern pattern = Pattern.compile(pat.toString());
        if (!pattern.matcher(str).matches()) {
            return false;
        } else {// 排除如00.1,返回false
            if (str.indexOf(".") != -1 && str.substring(0, str.indexOf(".")).length() > 1 && Integer.valueOf(str.substring(0, str.indexOf("."))) == 0) {
                return false;
            } else {
                return true;
            }
        }
    }

    /**
     * 功能：查看字符串是否有这个子字符串
     *
     * @param str    主字符串
     * @param substr 字字符串
     * @return
     */
    public static boolean hasSubstring(String str, String substr) {
        if (str == null || substr == null)
            return false;
        int strLen = str.length();
        int substrLen = substr.length();
        for (int i = 0; (i + substrLen) <= strLen; i++) {
            if (str.substring(i, i + substrLen).equalsIgnoreCase(substr)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 功能：字符串不以"/"结尾，则在串尾加"/"
     *
     * @param s
     * @return
     */
    public static String addSlashInEnd(String s) {
        if (s != null) {
            if (!s.endsWith("/")) {
                s = s + "/";
            }
        }
        return s;
    }

    /**
     * 功能：传入一个数字类型的参数，返回一个小数点后两位的小数
     *
     * @param parm
     */
    public static String ConverDouble(String parm) {
        if (isNumeric(parm, false, true)) {
            if (parm.indexOf(".") >= 0) {
                String value = parm.substring(parm.indexOf(".") + 1);
                if (value.length() == 1) {
                    return parm + "0";
                } else if (value.length() > 2) {
                    return parm.substring(0, parm.indexOf(".") + 1) + value.substring(0, 2);
                } else {
                    return parm;
                }

            } else {
                return parm + ".00";
            }
        }
        return null;
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0)
            return true;
        for (int i = 0; i < strLen; i++)
            if (!Character.isWhitespace(str.charAt(i)))
                return false;

        return true;
    }

    /**
     * 功能：截取某个字符串左边的部分，例 D:\a\bb.txt ==> \左边D:
     *
     * @param input
     * @param leftStr
     * @return
     */
    public static String subLeft(String input, String leftStr) {
        if (isEmpty(input, leftStr))
            return input;
        int left = input.indexOf(leftStr);
        if (left == -1)
            return null;
        String retString = input.substring(0, left);
        return retString;
    }

    /**
     * 功能：截取某个字符串右边的部分，例 D:\a\bb.txt ==> \右边bb.txt
     *
     * @param input
     * @param rightStr
     * @return
     */
    public static String subRight(String input, String rightStr) {
        if (isEmpty(input, rightStr))
            return input;
        int right = input.lastIndexOf(rightStr);
        if (right == -1)
            return null;
        else
            right = right + rightStr.length();
        String retString = input.substring(right);
        return retString;
    }

    public static int toInt(String intString, int defValue) {
        try {
            return (int) Float.parseFloat(intString);
        } catch (Exception e) {
            return defValue;
        }
    }

    /**
     * 功能：String转换成int类型
     *
     * @param intString
     * @return
     */
    public static int toInt(String intString) {
        return toInt(intString, 0);
    }

    public static boolean isInt(String intString) {
        try {
            Integer.parseInt(intString);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 功能：字符串不以"/"结尾，则在串尾加"/";字符串如果以/开头,则去掉第一个/
     *
     * @return
     */
    public static String dealSlash(String s) {
        if (s != null) {
            s = s.trim();
            if (!s.endsWith("/")) {
                s = s + "/";
            }
            if (s.startsWith("/")) {
                s = s.substring(1, s.length());
            }
        } else {
            s = "";
        }
        return s;

    }

    public static String lpad(String str, int length, char pad) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < length - str.length(); i++) {
            buffer.append(pad);
        }
        buffer.append(str);

        return buffer.toString();
    }

    public static String rpad(String str, int length, char pad) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(str);
        for (int i = 0; i < length - str.length(); i++) {
            buffer.append(pad);
        }

        return buffer.toString();
    }

    public static byte[] long2Bytes(long num) {
        byte[] byteNum = new byte[8];
        for (int ix = 0; ix < 8; ++ix) {
            int offset = 64 - (ix + 1) * 8;
            byteNum[ix] = (byte) ((num >> offset) & 0xff);
        }
        return byteNum;
    }

    public static long bytes2Long(byte[] byteNum) {
        long num = 0;
        for (int ix = 0; ix < 8; ++ix) {
            num <<= 8;
            num |= (byteNum[ix] & 0xff);
        }
        return num;
    }

    public static void main(String[] args) {
//		String b = "145551555555";
//		System.out.println(securityProduce(4));
        String[] strArr = new String[]{"k达林"};
        for (String str : strArr) {
            System.out.println("===========> 测试字符串：" + str);
            System.out.println("正则判断结果：" + isChineseByREG(str) + " -- " + isChineseByName(str));
            System.out.println("Unicode判断结果 ：" + isChinese(str));
            System.out.println("详细判断列表：");
            char[] ch = str.toCharArray();
            for (int i = 0; i < ch.length; i++) {
                char c = ch[i];
                System.out.println(c + " --> " + (isChinese(c) ? "是" : "否"));
            }
        }
    }

    /**
     * replace("{} are double {}","two","one") return( two are double one)
     *
     * @param source
     * @param args
     * @return
     */
    public static String replace(String source, String... args) {
        StringBuilder sb = new StringBuilder(source);
        for (int i = 0; i < args.length; i++) {
            sb.replace(sb.indexOf("{}"), sb.indexOf("{}") + 2, args[i]);
        }
        return sb.toString();
    }


    // 根据Unicode编码完美的判断中文汉字和符号
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    // 完整的判断中文汉字和符号
    public static boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    // 只能判断部分CJK字符（CJK统一汉字）
    public static boolean isChineseByREG(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("[\\u4E00-\\u9FBF]+");
        return pattern.matcher(str.trim()).find();
    }

    // 只能判断部分CJK字符（CJK统一汉字）
    public static boolean isChineseByName(String str) {
        if (str == null) {
            return false;
        }
        // 大小写不同：\\p 表示包含，\\P 表示不包含
        // \\p{Cn} 的意思为 Unicode 中未被定义字符的编码，\\P{Cn} 就表示 Unicode中已经被定义字符的编码
        String reg = "\\p{InCJK Unified Ideographs}&&\\P{Cn}";
        Pattern pattern = Pattern.compile(reg);
        return pattern.matcher(str.trim()).find();
    }


    /**
     * 判断是否为全数字
     *
     * @param str
     * @param count 数量
     * @return
     */
    public static boolean isNumeric(String str, int count) {
        if (str.length() < 9 || str.length() > 9) {
            return false;
        }
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 字符串 替换
     * 你好，{}!
     *
     * @param str
     * @param arr
     * @return
     */
    public static String fillStringByArgs(String str, Object... arr) {
        if (arr == null) {
            arr = new Object[0];
        }
        Matcher m = Pattern.compile("\\{\\}").matcher(str);
        int index = 0;
        while (m.find() && index < arr.length) {
            Object obj = arr[index++];
            str = str.replaceFirst("\\{\\}", obj == null ? "" : String.valueOf(obj));
        }
        return str.replaceAll("\\{\\}", "");
    }
}
